package cn.felord.wepay.spring.boot.autoconfigure;

import cn.felord.wepay.common.pay.Decryptable;
import cn.felord.wepay.common.pay.PayConfig;
import cn.felord.wepay.common.pay.Payable;
import cn.felord.wepay.wechat.entity.WeChatPayConfig;
import cn.felord.wepay.wechat.service.WeChatPayClient;
import org.apache.commons.lang3.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Dax
 * @version v1.0.0
 * @since 2017 /9/4  17:57
 */
@Configuration
@ConditionalOnClass(WeChatPayConfig.class)
@EnableConfigurationProperties({WePayProperties.class})
public class WePayAutoConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(WePayAutoConfiguration.class);
    @Resource
    private WePayProperties wePayProperties;


    /**
     * init client.
     *
     * @return the payable
     */
    @Bean
    @ConditionalOnMissingBean(PayConfig.class)
    public Payable client() {
        String appId = wePayProperties.getAppId();
        String mchId = wePayProperties.getMchId();
        String secretKey = wePayProperties.getSecretKey();
        String notifyUrl = wePayProperties.getNotifyUrl();
        String certPath = wePayProperties.getCertPath();
        String signType = wePayProperties.getSignType();
        String devMode = wePayProperties.getDevMode();
        String className = wePayProperties.getDecryptableClassName();
        Decryptable decryptable = null;
        if (className != null && !"".equals(className)) {
            try {
                Class decryptableClass = ClassUtils.getClass(className);
                decryptable = (Decryptable) decryptableClass.newInstance();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                LOGGER.debug("实例化解密类失败", e);
            }
        }
        PayConfig payConfig = new WeChatPayConfig.Builder(decryptable, appId, secretKey, mchId, signType, certPath, notifyUrl, devMode).build();
        return new WeChatPayClient(payConfig);
    }


}
